package com.chwn.curiousdiary.ui.story.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.adapter.StoryListAdapter;
import com.chwn.curiousdiary.adapter.StoryPackageAdapter;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.bean.StoryListBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.service.AudioService;
import com.chwn.curiousdiary.ui.story.contract.StoryListContract;
import com.chwn.curiousdiary.ui.story.presenter.StoryListPresenter;
import com.chwn.curiousdiary.ui.story.activity.StoryTypeActivity;
import com.chwn.curiousdiary.ui.play.activity.StoryPlayActivity;
import com.chwn.harulib.adapter.ViewHolder;
import com.chwn.harulib.adapter.interfaces.OnItemClickListener;
import com.chwn.harulib.adapter.interfaces.OnMultiItemClickListeners;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.mvp.rx.HttpResultException;
import com.chwn.harulib.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by Myshikin on 2017/4/11.
 * desc : 首页对应分类下的故事包界面
 */
public class StoryListFragment extends BaseMVPFragment<StoryListPresenter> implements StoryListContract.View, XRecyclerView.LoadingListener {
    @BindView(R.id.xrv_message)
    XRecyclerView mContentRV;

    private String mStoryType;
    private String mAllCount;
    private int     page      = 1;
    private boolean isRefresh = true;
    private int mJumpTag;

    private StoryListAdapter    mStoryListAdapter;
    private StoryPackageAdapter storyPackageAdapter;

    private TextView mAllCountTV;

    private static final int S_TAG_POSTION = 8;

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_storylist;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle arguments = getArguments();
        if (arguments != null) {
            mStoryType = arguments.getString(Constant.STORY_LIST, "0");
            mJumpTag = arguments.getInt(Constant.JUMP_TYPE, 0);
            mAllCount = arguments.getString(Constant.STORY_COUNT);
        }
    }

    @Override
    protected void initContentView() {
        ButterKnife.bind(this, mInflateContentView);
        if (mJumpTag == S_TAG_POSTION) {
            storyPackageAdapter = new StoryPackageAdapter(mActivity, null, false, mJumpTag);
            mContentRV.setLayoutManager(new GridLayoutManager(mActivity, 2));
            mContentRV.addItemDecoration(new SpaceItemDecoration(0));
            mContentRV.setAdapter(storyPackageAdapter);
        } else {
            mStoryListAdapter = new StoryListAdapter(mActivity, null, true);
            mContentRV.setLayoutManager(new LinearLayoutManager(mActivity));
            mContentRV.setAdapter(mStoryListAdapter);
        }
        if (mJumpTag < 6) {
            View headView = LayoutInflater.from(mActivity).inflate(R.layout.layout_story_count, null);
            mContentRV.setBackgroundColor(getResources().getColor(R.color.app_bg_gray));
            mAllCountTV = (TextView) headView.findViewById(R.id.tv_all_count);
            mAllCountTV.setText("共" + 0 + "个故事");
            mContentRV.addHeaderView(headView);
            initAllCount();
        }
        mContentRV.setLoadingListener(this);

        if ("-2".equals(mStoryType)) {
            mContentRV.setLoadingMoreEnabled(false);
            mStoryListAdapter.setNeedShowTag(true);
        } else {
            mContentRV.setLoadingMoreEnabled(true);
        }

        initStateViewData();
    }

    private void initAllCount() {
        mPresenter.getStoryTypeCount(mStoryType);
    }

    private void initStateViewData() {
        setEmptyView(R.drawable.icon_no_data);
        setErrorView(R.drawable.icon_no_data);
        setErrorText("哎呀，快去检查一下网络吧～");
        setEmptyText("没有故事～");
    }

    @Override
    protected void initListener() {
        super.initListener();
        if (mJumpTag == S_TAG_POSTION) {
            storyPackageAdapter.setOnMultiItemClickListener(new OnMultiItemClickListeners<StoryListBean>() {
                @Override
                public void onItemClick(ViewHolder viewHolder, StoryListBean data, int position, int viewType) {
                    onStoryListItemClick(data, position);
                }
            });
        } else {
            mStoryListAdapter.setOnItemClickListener(new OnItemClickListener<StoryListBean>() {
                @Override
                public void onItemClick(ViewHolder viewHolder, StoryListBean data, int position) {
                    onStoryListItemClick(data, position);
                }
            });
        }


    }

    private void onStoryListItemClick(StoryListBean data, int position) {
        if (data.getsParts() == 2) { //故事包
            enterStoryType(data);
        } else { //故事
            enterStoryPlay(position);
        }
    }

    /**
     * 进入播放界面
     */
    private void enterStoryPlay(int position) {
        List<StoryListBean> datas;

        if (mJumpTag == S_TAG_POSTION) {
            datas = storyPackageAdapter.getDatas();
        } else {
            datas = mStoryListAdapter.getDatas();
        }

        ArrayList<StoryBean> storyList = new ArrayList<>();
        int mark = 0;
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).getsParts() == 1) {
                storyList.add(new StoryBean(datas.get(i)));
            } else if (datas.get(i).getsParts() == 2) {
                mark++;
            }
        }

        Intent intent = new Intent(getActivity(), StoryPlayActivity.class);
        intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.NEWEST_ENTER);
        intent.putExtra(Constant.PACKAGE_ID, mStoryType);
        intent.putExtra("list", storyList);
        intent.putExtra("position", position - mark);
        intent.putExtra("bg_type", mJumpTag);
        startActivity(intent);
    }

    /**
     * 进入故事集的列表界面
     * @param data
     */
    private void enterStoryType(StoryListBean data) {
        Intent intent = new Intent(getActivity(), StoryTypeActivity.class);
        intent.putExtra(Constant.JUMP_TYPE, data.getStoryPackageId());
        intent.putExtra(Constant.STORY_LIST, data.getStoryPackageTitle());
        startActivity(intent);
    }

    @Override
    protected void getData() {
        mPresenter.getStoryList(mStoryType, page);
    }

    @Override
    public void onRequestError(Throwable e) {
        super.onRequestError(e);
        if (!isRefresh && e instanceof HttpResultException) {
            mContentRV.loadMoreComplete();
            mContentRV.refreshComplete();
            mContentRV.noMoreLoading();
            page--;
        } else if (e instanceof HttpResultException) {
            mContentRV.noMoreLoading();


            if (mJumpTag == S_TAG_POSTION) {
                if (storyPackageAdapter.getDatas() == null || storyPackageAdapter.getDatas().size() < 1) {
                    showEmptyView();
                }
            } else {
                if (mStoryListAdapter.getDatas() == null || mStoryListAdapter.getDatas().size() < 1) {
                    showEmptyView();
                }
            }
        } else {

            if (mJumpTag == S_TAG_POSTION) {
                if (storyPackageAdapter.getDatas() == null || storyPackageAdapter.getDatas().size() < 1) {
                    showErrorView();
                }
            } else {
                if (mStoryListAdapter.getDatas() == null || mStoryListAdapter.getDatas().size() < 1) {
                    showErrorView();
                }
            }
        }
    }

    @Override
    public void showStoryList(List<StoryListBean> storyList) {
        showContentView();
        if (mJumpTag == S_TAG_POSTION) {
            if (isRefresh) {
                storyPackageAdapter.setNewData(storyList);
                mContentRV.refreshComplete();
            } else {
                storyPackageAdapter.setLoadMoreData(storyList);
                mContentRV.loadMoreComplete();
            }
        } else {
            if (isRefresh) {
                mStoryListAdapter.setNewData(storyList);
                mContentRV.refreshComplete();
            } else {
                mStoryListAdapter.setLoadMoreData(storyList);
                mContentRV.loadMoreComplete();
            }
        }

        if (storyList.size() < Constant.PAGE_COUNT) {
            mContentRV.noMoreLoading();
        }
    }

    @Override
    public void showStoryTypeCount(int storyTypeCount) {
        mAllCount = storyTypeCount + "";
        mAllCountTV.setText("共" + mAllCount + "个故事");
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        isRefresh = false;
        page++;
        getData();
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.bottom = space;
        }
    }

    /**
     * 事件响应
     * @param event
     */
    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.UPDATE_COLLECT:
                int state = event.getPosition();
                String storyId = (String) event.getMessage();
                if (mStoryListAdapter != null) {
                    List<StoryListBean> datas = mStoryListAdapter.getDatas();
                    for (StoryListBean bean : datas) {
                        if (storyId.equals(bean.getStoryId())) {
                            bean.setStroyCollectionState(state);
                        }
                    }
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
